import parse from "@rojer/katex-mini";

// 是否是katex公式
export const isKatexStr = (str: string, isSplit = false) => {
  // 正则表达式匹配KaTeX公式
  const katexRegex = /(\$[^\$]*\$)|(\\\([^\\)]*\\\))/g;
  if (isSplit && str.indexOf(`\\`) !== -1) {
    return true;
  }
  if (katexRegex.test(str)) {
    return true;
  }
  return false;
};

// 处理katex公式字符串
export const handleKatexStr = (str: string) => {
  let handleStr = `${str}`;
  handleStr = handleStr.replace(/\$/g, "");
  handleStr = handleStr.replace(/<[^>]*>/g, ""); //移除所有的html标签
  handleStr = `\\displaystyle ${handleStr}`;

  const parseNodes = parse(handleStr);
  let parseResult = "success";
  if (parseNodes && parseNodes.length > 0) {
    const children = parseNodes[0].children;
    if (children && children.length > 0) {
      const item = children[0];
      if (
        item &&
        item.type === "text" &&
        item.text.indexOf("KaTeX parse error") !== -1
      ) {
        parseResult = "fail";
      }
    }
  }
  if (parseResult === "success") {
    return parseNodes || str;
  }
  return str;
};
